﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using Newtonsoft.Json;
using ZLCMS.Commands.Data;

namespace ZLCMS.Web.SystemManage.Basics.Shop.ChargeCard
{
    public partial class ChargeCardRuleDetail : System.Web.UI.Page
    {
        protected ShopCouponRule item = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int uid = 0;

                if (Int32.TryParse(Request["uid"], out uid))
                {

                }
                
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    item = session.Get<ShopCouponRule>(uid);
                    if (item != null)
                    {
                        //保存uid
                        ViewState["uid"] = uid;
                    }
                    else
                    {
                        item = new ShopCouponRule();
                        item.Status = "0";
                        item.StartGetDate = DateTime.Now;
                        item.EndGetDate = DateTime.Now.AddDays(15);
                    }
                }

                //设置控件值
                ParamKit.Bind("YesNo_10", ddl_create, null, null, null, "1", null);

                title.Text = item.Title;
                start.Text = string.Format("{0}", item.StartGetDate);
                end.Text = string.Format("{0}", item.EndGetDate);

                imageUrl.Value = item.ImageUrl;
                txtContent.Value = item.Memo;
                summary.Text = item.Summary;
                limitday.Text = string.Format("{0}", item.LimitDay);
                limitcount.Text = string.Format("{0}", item.LimitCount);
                backgroundUrl.Value = item.BackgroundUrl;

                txt_counter.Text = string.Format("{0}", item.AutogenerationCount);

                //初始化规则 
                CouponRuleItem ruleItem = null;
                try
                {
                    ruleItem = JsonConvert.DeserializeObject<CouponRuleItem>(item.ItemConfig);
                }
                catch
                {

                }
                if (ruleItem != null)
                {
                    txt_amount.Text = string.Format("{0}", ruleItem.Amount);
                    txt_start.Text = ruleItem.Start.ToString();
                    txt_end.Text = ruleItem.End.ToString();
                    txt_memo.Text = ruleItem.Memo;
                    txt_title.Text = ruleItem.Title;
                    ddl_create.SelectedValue = item.IsAutogeneration;
                    txt_ahead.Text = ruleItem.Code;

                    if (item.Status != "0")
                    {
                        txt_amount.ReadOnly = true;
                        txt_counter.ReadOnly = true;
                        txt_start.ReadOnly = true;
                        txt_end.ReadOnly = true;
                        txt_title.ReadOnly = true;
                        ddl_create.Enabled = false;
                        txt_ahead.ReadOnly = true;
                    }
                    else
                    {
                        txt_start.CssClass = "date required";
                        txt_end.CssClass = "date required";
                    }
                }
                else
                {
                    txt_amount.Text = "0";
                    txt_counter.Text = "100";
                    txt_start.Text = string.Format("{0}", DateTime.Now);
                    txt_end.Text = string.Format("{0}", DateTime.Now.AddDays(15));
                }
            }
            else
            {

                int uid = ViewState["uid"] == null ? 0 : (int)ViewState["uid"];
                
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    item = session.Get<ShopCouponRule>(uid);
                    if (item == null)
                    {
                        item = new ShopCouponRule();
                        item.Status = "0";
                        item.CreateDate = DateTime.Now;
                        item.OwnerAccount = UserKit.GetUserAccountFailLogin();
                    }

                    //在此设置item的各个属性
                    item.Title = title.Text;

                    item.IsAutogeneration = ddl_create.SelectedValue;
                    item.StartGetDate = DateTime.Parse(start.Text);
                    item.EndGetDate = DateTime.Parse(end.Text);
                    item.LimitDay = Convert.ToInt32(limitday.Text);
                    item.LimitCount = Convert.ToInt32(limitcount.Text);
                    item.AutogenerationCount = Convert.ToInt32(txt_counter.Text);

                    //充值卡规则
                    if (item.Status == "0")
                    {
                        //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                        item.ItemConfig = JsonConvert.SerializeObject(new ChargeCardItem()
                        {
                            Amount = int.Parse(txt_amount.Text),
                            Code = txt_ahead.Text,
                            Counter = int.Parse(txt_counter.Text),
                            Start = DateTime.Parse(txt_start.Text),
                            End = DateTime.Parse(txt_end.Text),
                            Memo = txt_memo.Text,
                            Title = txt_title.Text
                        });
                    }

                    item.CouponType = "chargecard";
                    item.BackgroundUrl = backgroundUrl.Value;
                    //itemGrid.Readonly = item.Status == "0";
                    item.ImageUrl = imageUrl.Value;
                    item.Memo = txtContent.Value;
                    item.Summary = summary.Text;
                    //item.IsAutogeneration = cbk_is_autogeneration.Checked ? "1" : "0";


                    WxMaterial mat = session.Get<WxMaterial>(item.MaterialId);
                    if (mat == null)
                    {
                        mat = new WxMaterial();
                        mat.CreateDate = DateTime.Now;
                    }
                    mat.MsgType = "chargecard";
                    mat.OwnerAccount = UserKit.GetUserAccountFailLogin();
                    mat.Status = "1";
                    mat.Title = item.Title;
                    mat.UpdateDate = DateTime.Now;
                    session.SaveOrUpdate(mat);

                    WxMaterialNews news = session.CreateQuery("from WxMaterialNews where MaterialId=:mid").SetParameter("mid", mat.Id)
                        .UniqueResult<WxMaterialNews>();
                    if (news == null)
                    {
                        news = new WxMaterialNews();
                    }
                    news.Content = item.Summary;
                    news.ContentType = "URL";
                    news.Description = item.Summary;
                    news.MaterialId = mat.Id;
                    news.OwnerAccount = UserKit.GetUserAccountFailLogin();
                    news.Title = item.Title;
                    session.SaveOrUpdate(news);

                    item.MaterialId = mat.Id;

                    //保存并更新item
                    session.SaveOrUpdate(item);
                    session.Flush();
                }

                //框架返回成功提示
                ZLCMS.Business.DwzFrame.FrameHelper _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);
                ZLCMS.Business.DwzFrame.ReturnCode rc = new ZLCMS.Business.DwzFrame.ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功"
                };

                rc.callbackType = "forward";
                rc.forwardUrl = "/SystemManage/Basics/Shop/ChargeCard/ChargeCardRuleDetail.aspx?tabid=CouponRuleDetail";

                if (Request["submit_op"] != "1")
                {
                    rc.forwardUrl += "&uid=" + item.Id;
                }

                _framePage.Alert(rc);
            }
        }
    }
}